//引入系统库
var path = require("path");
var crypto = require("crypto"); //加密验证

//插件框架
var express = require("express");
var passport = require("passport");
var Strategy = require("passport-local").Strategy;
var bodyParser = require("body-parser");

//引入数据模型（用于数据库交互）
var user = require("../models/user");
var settings = require("../config/settings");

var router = express.Router();

var urlencodedParser = bodyParser.urlencoded({ extended: false });

passport.use(
  "local",
  new Strategy(
    {
      usernameField: "username", //页面上的用户名字段的name属性值
      passwordField: "password" //页面上的密码字段的name属性值
    },
    function(username, password, cb) {
      var md5 = crypto.createHash("md5");
      md5.update(password);
      var sign = md5.digest("hex");
      console.log(username);
      user.findOne({ name: username, password: sign }, function(err, doc) {
        if (doc) {
          //验证通过
          return cb(null, doc);
        } else {
          //验证不通过
          return cb(null, false);
        }
      });
    }
  )
);

//序列化保存
passport.serializeUser(function(user, cb) {
  cb(null, user.id);
}); //req.session.passport.user={id:""}
//解码序列化
passport.deserializeUser(function(id, cb) {
  //  cb(null, user);
  user.findById(id, function(err, user) {
    cb(err, user);
  });
}); //通过req.session.passport.user的id去查找数据库，找到user的相关信息

//登录页面
router.get("/login", function(req, res, next) {
  res.render("auth", {
    layout: "other",
    login: true,
    config: settings,
    title: settings["SiteName"] + " - " + res.__("auth.title")
  });
});

router.get("/register", function(req, res, next) {
  res.render("auth", {
    layout: "other",
    login: false,
    config: settings,
    title: settings["SiteName"] + " - " + res.__("auth.title")
  });
});

//提交登录请求
router.post("/login", urlencodedParser, function(req, res, next) {
  passport.authenticate("local", function(err, user, info) {
    if (err) {
      next(err);
    } else if (!user) {
      res.json({
        code: -1
      });
    } else {
      //登录操作
      req.logIn(user, function(err) {
        var returnTo = "/editor";
        if (err) {
          next(err);
        } else {
          //尝试跳转之前的页面
          if (req.session.returnTo) {
            returnTo = req.session.returnTo;
          }
          res.json({
            code: 0,
            goto: returnTo
          });
        }
      });
    }
  })(req, res, next);
});

//退出登录
router.post("/logout", function(req, res) {
  req.logout();
  res.json({
    code: 0,
    goto: "/"
  });
});

//注册
router.post("/register", urlencodedParser, function(req, res) {
  var username = req.body.username;
  var password = req.body.password;
  //加密
  var md5 = crypto.createHash("md5");
  md5.update(password);
  var sign = md5.digest("hex");
  user.create(
    {
      name: username,
      password: sign
    },
    function(err, doc) {
      //res.send({ code: 0 });
      //res.redirect("/login");
      res.json({
        code: 0,
        goto: "/"
      });
    }
  );
});

module.exports = router;
